import {
  Box, Button, Checkbox, Flex, FormControl, FormLabel, Input, InputGroup,
  InputLeftAddon, InputLeftElement, InputRightAddon, Radio, RadioGroup,
  Select, SelectField, Stack, Switch, Text
} from '@chakra-ui/react'
import { FaUserAlt, FaLock, FaCheck } from 'react-icons/fa'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import * as Yup from 'yup'
import axios from 'axios'

export default function SignIn() {
  const initialValues = { username: '', password: '' }
  // const initialValues = { username: 'jake@jake.jake111111', password: 'jakejake' }
  const handleSubmit = async (values, actions) => {
    const postUrl = "https://conduit.productionready.io/api/users/login"
    const params = {"user":{"email": values.username, "password": values.password}}
    try
    {
      const {data} = await axios.post(postUrl, params)
      if(data.user.token) {
        alert("登录成功")
      }
    }catch({error, response}){
      if(response.status && response.status == 422) {
        actions.setFieldError('username','请输入正确的用户名和密码')
      }
    }
  }
  const validationSchema = Yup.object({
    username: Yup.string().max(25, '用户名长度不能大于25').required('用户名不能为空'),
    password: Yup.string().min(6, '密码长度不能小于6').required('密码不能为空'),
  })
  const getComponent = (props) => {
    let errorCom = null
    if (props.errors.username || props.errors.password) {
      errorCom = <div>{props.errors.username || props.errors.password}</div>
    }
    return (
      <Form>
        <Stack direction="column" spacing={4}>
          {errorCom ? errorCom : null}
          <Stack spacing={0}>
            <Field name="username">
              {
                ({field, form}) => {
                  // console.log(form)
                  return (
                    <FormControl>
                      <InputGroup>
                        <InputLeftElement pointerEvents="none" children={<FaUserAlt />} />
                        <Input {...field} borderRadius="5px 5px 0 0" placeholder="手机号或邮箱" />
                      </InputGroup>
                    </FormControl>
                  )
                }

              }
            </Field>
            <Field name="password">
              {
                ({field, form}) => {
                  // console.log(form)
                  return (
                    <FormControl>
                    <InputGroup>
                      <InputLeftElement pointerEvents="none" children={<FaLock />} />
                      <Input {...field} borderRadius="0 0 5px 5px" placeholder="密码" />
                    </InputGroup>
                  </FormControl>
                  )
                }
              }
            </Field>

          </Stack>
          <Stack direction="row" textAlign="right">
            <Stack w="100%">
              <Checkbox defaultIsChecked>记住我</Checkbox>
            </Stack>
            <Box as="span" w="100%">登录遇到问题?</Box>
          </Stack>
          <Button type="submit" _hover={{ bg: "tomato" }} borderRadius="50px" colorScheme="blue">登录</Button>
        </Stack>
      </Form>
    )
  }
  return(
    <Formik validateOnBlur={false} validateOnChange={false} initialValues={initialValues} 
    onSubmit={handleSubmit} validationSchema={validationSchema}>
    {
      getComponent
    }
    </Formik>
    )
}